#!/usr/bin/env python
#
#    Copyright (C) 2013 Gonzalo Bonigo <gonzalobonigo@gmail.com>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see http://www.gnu.org/licenses/
#


import os.path
import sys
import os

from daddydir import *


class DaddyInstallErrors(Exception):
    pass


def _copy_file (src, des, attr):
    # Open source file.
    read_file = open(src, "rb")
    try:
        # Open destination file.
        write_file = open(des, "wb")
    except (OSError,IOError) as error:
        # If it fails we close source file.
        read_file.close()
        raise DaddyInstallErrors(error)
    try:
        # Copy data from source to destination file.
        write_file.write(read_file.read())
    except (OSError,IOError) as error:
        # If it fails we close all files.
        read_file.close()
        write_file.close()
        # and remove destination file.
        os.remove(des)
        raise DaddyInstallErrors(error)
    # Close files.
    read_file.close()
    write_file.close()
    # Change attributes.
    try:
        if SYSTEM == 'Linux':
            os.chmod(des, attr)
    except (OSError,IOError), (error):
        raise DaddyInstallErrors(error)


def _install_package (pkg_name):
    # Check if it's already installed.
    if os.path.exists(PKG_DIR+pkg_name):
        raise DaddyInstallErrors("Package already installed:", pkg_name)
    # If it's not installed, we create its directory.
    try:
        os.mkdir(PKG_DIR + pkg_name)
    except (OSError,IOError) as error:
        raise DaddyInstallErrors(error)
    # Set permission.
    try:
        os.chmod(PKG_DIR + pkg_name, PKG_DIR_ATTR)
    except (OSError,IOError) as error:
        # If it fails, we remove the directory.
        os.rmdir(PKG_DIR + pkg_name)
        raise DaddyInstallErrors(error)
    # List of sub-packages.
    list_sub_pkg = []
    # List of copied files.
    list_copied_files = []
    # Copy all files and install sub-packages.
    try:
        for entry in os.listdir(DADDY_DIR + pkg_name):
            if os.path.isdir(DADDY_DIR + pkg_name + os.sep + entry):
                list_sub_pkg.append(pkg_name + os.sep + entry)
            else:
                if not entry.endswith('~'):
                    src = DADDY_DIR + pkg_name + os.sep + entry
                    des = PKG_DIR + pkg_name + os.sep + entry
                    _copy_file(src, des, NORM_FILE_ATTR)
                    list_copied_files.append(des)
    except (OSError,IOError) as error:
        # If some copy fails, we remove all copied files.
        for f in list_copied_files:
            os.remove(f)
        # and the directory.
        os.rmdir(PKG_DIR + pkg_name)
        raise DaddyInstallErrors(error)
    # Install all sub-packages.
    for pkg in list_sub_pkg:
        _install_package(pkg)


if __name__ == '__main__':
    print "\n--- Initiating installation ---\n"
    # --- Check system ---
    print "Checking system compatibility..."
    if not SYSTEM in ['Windows','Linux']:
        print "\n*** Operating System not supported! ***\n"
        print "DADDY can only be automatic install on Linux or Windows.\n"
        print "Found: " + SYSTEM + '\n'
        sys.exit(0)
    else:
        print " -Installing on", SYSTEM
    print "OK\n"
    # --- Check version ---
    print "Checking version..."
    if sys.version_info.major != 2:
        print "\nFATAL ERROR - DADDY needs at least Python version 2.\n"
        print "Found: Python " + sys.version.split()[0] + '\n'
        sys.exit(0)
    elif sys.version_info.minor != 7:
        print "\nWARNING! - DADDY was built for Python version 2.7\n"
        print "Found: Python " + sys.version.split()[0] + '\n'
    else:
        print " -version", sys.version.split()[0]
        print "OK\n"
    # --- Copy executable files ----
    print "Coping executable files..."
    try:
        for f in EXEC_FILE_LIST:
            print "*", DADDY_DIR+f, ">", EXEC_DIR+f
            _copy_file(DADDY_DIR+f, EXEC_DIR+f, EXEC_FILE_ATTR)
    except DaddyInstallErrors, (error):
        print str(error) + '\n'
        print "--- Installation fails ---\n"
        sys.exit(0)
    print "Done!\n"
    # --- Installing packages ---
    print "Installing packages..."
    try:
        for p in PKG_LIST:
            print "*", DADDY_DIR+p, ">", PKG_DIR+p
            _install_package(p)
    except DaddyInstallErrors, (error):
        print str(error) + '\n'
        print "--- Installation fails ---\n"
        sys.exit(0)
    print "Donde!\n"
    print "--- Installation completed ---\n"
